﻿<script setup lang="ts" name="MonitResize">
import { templateRef, useResizeObserver, useDebounceFn } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'

const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)
const route = useRoute()
const itemWidth = ref(0)
const itemHeight = ref(0)
// 获取当前页面的缓存状态是否被开启
const isKeepAlive = route.meta.keepAlive && systemConfig.value.isKeepAlive

const bodyWidth = ref(0)
const bodyHeight = ref(0)
const monitBodyResize = () => {
  const rect = document.body.getBoundingClientRect()
  bodyWidth.value = rect.width
  bodyHeight.value = rect.height
}
// 监听元素尺寸变化
useResizeObserver(
  document.body,
  useDebounceFn(() => {
    monitBodyResize()
  }, 200)
)

const resizeCoreDom = templateRef<HTMLElement | null>('resizeCoreDom', null)
const coreWidth = ref(0)
const coreHeight = ref(0)
const monitCoreResize = () => {
  coreWidth.value = resizeCoreDom.value.offsetWidth
  coreHeight.value = resizeCoreDom.value.offsetHeight
}
// 监听元素尺寸变化
useResizeObserver(
  resizeCoreDom,
  useDebounceFn(() => {
    monitCoreResize()
  }, 200)
)
</script>

<template>
  <PageWrap>
    <el-space :size="systemConfig.space" fill direction="vertical">
      <el-card shadow="never" class="no-border no-radius">
        <div class="resize-container resize-body">
          <p>
            useResizeObserver监听body宽高变化: 宽：
            <span>{{ bodyWidth }}</span>
            、高：
            <span>{{ bodyHeight }}</span>
          </p>
        </div>
        <div class="resize-container resize-core">
          <div ref="resizeCoreDom" class="resize-core-content">
            <p>
              useResizeObserver监听元素宽高变化: 宽：
              <span>{{ coreWidth }}</span>
              、高：
              <span>{{ coreHeight }}</span>
            </p>
          </div>
        </div>
      </el-card>
    </el-space>
  </PageWrap>
</template>

<style scoped lang="scss">
.el-space {
  width: 100%;
  padding: var(--el-space) var(--el-space) 0;
}

.no-border {
  border: none;
}

.no-radius {
  border-radius: 0;
}

.el-card {
  display: flex;

  :deep(.el-card__body) {
    display: flex;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .resize-body {
      flex: 0 0 20%;
    }

    .resize-core {
      flex: 0 0 30%;
      padding: 0 10%;

      .resize-core-content {
        flex: 1;
      }
    }

    .resize-item {
      flex: 0 0 50%;
    }

    .resize-container,
    .resize-core-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;

      p {
        font-size: 24px;
        font-weight: bold;
        text-align: center;

        span {
          color: var(--el-color-primary);
        }
      }
    }
  }
}
</style>
